﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Hsp.WebNovels.Console.Utility
{
    /// <summary>
    /// Http请求帮助类
    /// </summary>
    public class HttpHelper
    {

        /// <summary>
        /// get同步請求
        /// </summary>
        /// <param name="uri">统一资源标志符(Uniform Resource Identifier，URI)</param>
        /// <returns></returns>
        public static string HttpGet(Uri uri)
        {
            GC.Collect(); //垃圾回收，回收没有正常关闭的http连接
            string retString = ""; //返回结果

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            try
            {
                //设置最大连接数，建议不要超过1024，推荐为512
                ServicePointManager.DefaultConnectionLimit = 512;

                request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "GET";
                request.Timeout = 5 * 1000;
                request.ContentType = "text/html;charset=UTF-8";
                //request.ContentType = "text/html;charset=gbk";
                response = (HttpWebResponse)request.GetResponse();
                using (Stream sr = response.GetResponseStream())
                {
                    StreamReader myStreamReader = new StreamReader(sr, Encoding.GetEncoding("utf-8"));
                    retString = myStreamReader.ReadToEnd();
                }
                return retString;
            }
            catch (System.Threading.ThreadAbortException abortException)
            {
                System.Console.WriteLine($"ThreadAbortException，{(string)abortException.ExceptionState}");
                //LogHelper.Info("HttpGet出错", $"ThreadAbortException，{(string)abortException.ExceptionState}");
                System.Threading.Thread.ResetAbort();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
                //LogHelper.Info("HttpGet出错", $"Exception，{ex.ToString()}");
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
                //if (sr != null)
                //{
                //    sr.Close();
                //}
                //if (reqStream != null)
                //{
                //    reqStream.Close();
                //}
            }
            return retString;

        }

        /// <summary>
        /// get同步請求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headers">請求頭</param>
        /// <returns></returns>
        public static string HttpGet(string url, Dictionary<string, string> headers = null)
        {
            using HttpClient client = new HttpClient();

            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }

            HttpResponseMessage response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }

        /// <summary>
        /// get異步請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null)
        {
            GC.Collect(); //垃圾回收，回收没有正常关闭的http连接
            string retString = ""; //返回结果

            HttpResponseMessage response = null;

            try
            {
                using HttpClient client = new HttpClient();

                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }

                response = await client.GetAsync(url);
                retString = await response.Content.ReadAsStringAsync();

                return retString;
            }
            catch (System.Threading.ThreadAbortException abortException)
            {
                //LogHelper.Info("HttpGet出错", $"ThreadAbortException，{(string)abortException.ExceptionState}");
                System.Threading.Thread.ResetAbort();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
                //LogHelper.Info("HttpGet出错", $"Exception，{ex.ToString()}");
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Dispose();
                }
            }
            return retString;
        }
    }
}
